package cn.fz.luck.saas.config.security;

import cn.fz.luck.saas.mapper.SysPermissionMapper;
import cn.fz.luck.saas.model.SysPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 授权:资源角色授权器
 * Created by zhuangqi on 17-7-6.
 */
@Service
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    private Map<String, Collection<ConfigAttribute>> resourceMap;

    //提取系统中的所有权限
    private void loadResourceMatchAuthority() {
        List<SysPermission> permissions = sysPermissionMapper.selectAll();
        resourceMap = new HashMap<>();
        for (SysPermission permission : permissions) {
            Collection<ConfigAttribute> list;
            if (resourceMap.containsKey(permission.getUrl())) {
                list = resourceMap.get(permission.getUrl());
                list.add(new SecurityConfig(permission.getUrl()+":"+permission.getMethod()));
                resourceMap.put(permission.getUrl(),list);
            } else {
                list = new ArrayList<>();
                list.add(new SecurityConfig(permission.getUrl()+":"+permission.getMethod()));
                resourceMap.put(permission.getUrl(),list);
            }
        }
    }

    // 根据URL，找到相关的权限配置。
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        HttpServletRequest request = fi.getRequest();
        System.out.println("================【requestUrl is ：" + fi.getRequestUrl()+"】==================");
        if (resourceMap == null) {
            loadResourceMatchAuthority();
        }
        Collection<ConfigAttribute> attrs = new ArrayList<ConfigAttribute>();
        for (Map.Entry<String, Collection<ConfigAttribute>> entry : resourceMap.entrySet()){
            String urlPattern  = entry.getKey();
            List<ConfigAttribute> configAttributes = new ArrayList<>(entry.getValue());
            String attribute = configAttributes.get(0).toString();
            String method = attribute.substring(attribute.indexOf(":")+1);
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(urlPattern);
            if (matcher.matches(request)) {
                if (method.equals(request.getMethod()) || "ALL".equals(method)) {
                    attrs.addAll(resourceMap.get(urlPattern));
                }
            }
        }
        return attrs;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
